import type { 
  User, 
  MonitoredTable, 
  DashboardStats, 
  FlinkJob, 
  ApiResponse, 
  PaginationResponse
} from '@/types'

// 模拟延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

// 模拟用户数据
const mockUser: User = {
  id: 1,
  username: 'admin',
  full_name: '系统管理员',
  is_active: true,
  last_login_at: '2024-01-15T10:00:00Z',
  created_at: '2024-01-01T00:00:00Z',
  updated_at: '2024-01-15T10:00:00Z'
}

// 模拟登录响应
const mockLoginResponse = {
  access_token: 'mock_access_token_12345',
  user: mockUser
}

// 模拟仪表板统计数据
const mockDashboardStats: DashboardStats = {
  total_tables: 1234,
  total_data_size: 2048576000,
  active_alerts: 12,
  running_jobs: 18,
  layers: [
    {
      layer: 'TDS',
      table_count: 12,
      total_rows: 500000000,
      total_size: 204857600,
      health_status: 'healthy',
      last_update: '2024-01-15T10:30:00Z'
    },
    {
      layer: 'ODS',
      table_count: 45,
      total_rows: 2000000000,
      total_size: 819430400,
      health_status: 'warning',
      last_update: '2024-01-15T10:25:00Z'
    },
    {
      layer: 'DWD',
      table_count: 32,
      total_rows: 1000000000,
      total_size: 409715200,
      health_status: 'healthy',
      last_update: '2024-01-15T10:28:00Z'
    },
    {
      layer: 'DWS',
      table_count: 18,
      total_rows: 500000000,
      total_size: 204857600,
      health_status: 'healthy',
      last_update: '2024-01-15T10:32:00Z'
    },
    {
      layer: 'DIM',
      table_count: 25,
      total_rows: 200000000,
      total_size: 81943040,
      health_status: 'healthy',
      last_update: '2024-01-15T10:35:00Z'
    },
    {
      layer: 'ADS',
      table_count: 15,
      total_rows: 100000000,
      total_size: 40971520,
      health_status: 'healthy',
      last_update: '2024-01-15T10:38:00Z'
    }
  ]
}

// 模拟监控表数据
const mockTables: MonitoredTable[] = [
  {
    id: 1,
    table_name: 'tds_by_talent_baiying_from_dyh',
    database_name: 'starrocks',
    layer: 'TDS',
    description: '抖音号搜索得到百应UID数据',
    is_active: true,
    monitor_interval: 300,
    alert_threshold: 1000,
    created_at: '2024-01-01T00:00:00Z',
    updated_at: new Date().toISOString(),
    is_monitored: true
  },
  {
    id: 2,
    table_name: 'ods_adb_dw_bd_order',
    database_name: 'starrocks',
    layer: 'ODS',
    description: 'ADB机构订单表',
    is_active: true,
    monitor_interval: 300,
    alert_threshold: 1000,
    created_at: '2024-01-01T00:00:00Z',
    updated_at: new Date().toISOString(),
    is_monitored: false
  },
  {
    id: 3,
    table_name: 'dwd_user_behavior_daily',
    database_name: 'starrocks',
    layer: 'DWD',
    description: '用户行为日汇总表',
    is_active: true,
    monitor_interval: 600,
    alert_threshold: 500,
    created_at: '2024-01-01T00:00:00Z',
    updated_at: new Date().toISOString(),
    is_monitored: true
  },
  {
    id: 4,
    table_name: 'dws_user_profile_summary',
    database_name: 'starrocks',
    layer: 'DWS',
    description: '用户画像汇总表',
    is_active: true,
    monitor_interval: 1800,
    alert_threshold: 200,
    created_at: '2024-01-01T00:00:00Z',
    updated_at: new Date().toISOString(),
    is_monitored: true
  },
  {
    id: 5,
    table_name: 'dim_product_category',
    database_name: 'starrocks',
    layer: 'DIM',
    description: '产品分类维度表',
    is_active: true,
    monitor_interval: 3600,
    alert_threshold: 50,
    created_at: '2024-01-01T00:00:00Z',
    updated_at: new Date().toISOString(),
    is_monitored: false
  },
  {
    id: 6,
    table_name: 'ads_daily_revenue_summary',
    database_name: 'starrocks',
    layer: 'ADS',
    description: '日收入汇总表',
    is_active: true,
    monitor_interval: 900,
    alert_threshold: 100,
    created_at: '2024-01-01T00:00:00Z',
    updated_at: new Date().toISOString(),
    is_monitored: true
  },
  {
    id: 7,
    table_name: 'ods_event_log',
    database_name: 'starrocks',
    layer: 'ODS',
    description: '事件日志明细',
    is_active: true,
    monitor_interval: 300,
    alert_threshold: 1000,
    created_at: '2024-01-01T00:00:00Z',
    updated_at: new Date().toISOString(),
    is_monitored: true
  },
  {
    id: 8,
    table_name: 'dwd_order_detail',
    database_name: 'starrocks',
    layer: 'DWD',
    description: '订单明细宽表',
    is_active: true,
    monitor_interval: 600,
    alert_threshold: 800,
    created_at: '2024-01-01T00:00:00Z',
    updated_at: new Date().toISOString(),
    is_monitored: true
  }
]

// 模拟Flink作业数据
const mockFlinkJobs: FlinkJob[] = [
  {
    id: 1,
    job_id: 'abc123',
    job_name: 'Api_Job_Kafka2SR_TDS',
    module_name: 'yc-api-job',
    jar_name: 'yc-api-job-1.0-SNAPSHOT.jar',
    jar_path: '/opt/flink/jars/yc-api-job-1.0-SNAPSHOT.jar',
    entry_class: 'com.jcm.ApiJob',
    last_status: 'RUNNING',
    auto_recovery: true,
    max_recovery_attempts: 3,
    recovery_attempts: 0,
    manual_stopped: false,
    savepoint_interval: 24,
    description: 'API数据采集作业',
    created_at: '2024-01-01T00:00:00Z',
    updated_at: new Date().toISOString(),
    last_check_time: new Date().toISOString(),
    last_running_time: new Date().toISOString(),
    health_status: 'HEALTHY',
    consecutive_failures: 0,
    total_failures: 0,
    version: 1
  },
  {
    id: 2,
    job_id: 'def456',
    job_name: 'Talent_Job_Data_Collection',
    module_name: 'yc-talent-job',
    jar_name: 'yc-talent-job-1.0-SNAPSHOT.jar',
    jar_path: '/opt/flink/jars/yc-talent-job-1.0-SNAPSHOT.jar',
    entry_class: 'com.jcm.TalentJob',
    last_status: 'RUNNING',
    auto_recovery: true,
    max_recovery_attempts: 3,
    recovery_attempts: 0,
    manual_stopped: false,
    savepoint_interval: 12,
    description: '达人数据采集作业',
    created_at: '2024-01-01T00:00:00Z',
    updated_at: new Date().toISOString(),
    last_check_time: new Date().toISOString(),
    last_running_time: new Date().toISOString(),
    health_status: 'HEALTHY',
    consecutive_failures: 0,
    total_failures: 0,
    version: 1
  },
  {
    id: 3,
    job_id: 'ghi789',
    job_name: 'Live_Job_Stream_Processing',
    module_name: 'yc-live-job',
    jar_name: 'yc-live-job-1.0-SNAPSHOT.jar',
    jar_path: '/opt/flink/jars/yc-live-job-1.0-SNAPSHOT.jar',
    entry_class: 'com.jcm.LiveJob',
    last_status: 'FINISHED',
    auto_recovery: false,
    max_recovery_attempts: 3,
    recovery_attempts: 0,
    manual_stopped: true,
    savepoint_interval: 6,
    description: '直播数据流处理作业',
    created_at: '2024-01-01T00:00:00Z',
    updated_at: new Date().toISOString(),
    last_check_time: new Date().toISOString(),
    last_running_time: new Date().toISOString(),
    health_status: 'UNHEALTHY',
    consecutive_failures: 2,
    total_failures: 5,
    version: 1
  },
  {
    id: 4,
    job_id: 'jkl012',
    job_name: 'Order_Job_ETL_Processing',
    module_name: 'yc-order-job',
    jar_name: 'yc-order-job-1.0-SNAPSHOT.jar',
    jar_path: '/opt/flink/jars/yc-order-job-1.0-SNAPSHOT.jar',
    entry_class: 'com.jcm.OrderJob',
    last_status: 'FAILED',
    auto_recovery: true,
    max_recovery_attempts: 3,
    recovery_attempts: 3,
    manual_stopped: false,
    savepoint_interval: 24,
    description: '订单ETL处理作业',
    created_at: '2024-01-01T00:00:00Z',
    updated_at: new Date().toISOString(),
    last_check_time: new Date().toISOString(),
    last_running_time: new Date().toISOString(),
    health_status: 'CRITICAL',
    consecutive_failures: 3,
    total_failures: 10,
    version: 1
  }
]

// 模拟API响应
export const mockApi = {
  // 认证相关
  auth: {
    login: async (username: string, password: string): Promise<ApiResponse<any>> => {
      await delay(500)
      
      if (username === 'admin' && password === 'admin123') {
        return {
          code: 200,
          message: 'Login successful',
          data: mockLoginResponse,
          timestamp: new Date().toISOString()
        }
      } else {
        throw new Error('Invalid credentials')
      }
    },
    
    logout: async (): Promise<ApiResponse<void>> => {
      await delay(200)
      return {
        code: 200,
        message: 'Logout successful',
        data: undefined,
        timestamp: new Date().toISOString()
      }
    },
    
    getProfile: async (): Promise<ApiResponse<User>> => {
      await delay(300)
      return {
        code: 200,
        message: 'success',
        data: mockUser,
        timestamp: new Date().toISOString()
      }
    }
  },
  
  // 监控相关
  monitor: {
    getDashboardStats: async (): Promise<ApiResponse<DashboardStats>> => {
      await delay(400)
      return {
        code: 200,
        message: 'success',
        data: mockDashboardStats,
        timestamp: new Date().toISOString()
      }
    },
    
    getTables: async (params?: any): Promise<ApiResponse<PaginationResponse<MonitoredTable>>> => {
      await delay(200)
      const { page = 1, size = 20, search = '', layer, is_monitored } = params || {}
      let items = mockTables.slice()
      if (search) {
        const s = String(search).toLowerCase()
        items = items.filter(t => (t.table_name?.toLowerCase().includes(s) || t.description?.toLowerCase().includes(s)))
      }
      if (layer) {
        items = items.filter(t => t.layer === layer)
      }
      if (is_monitored !== undefined && is_monitored !== '') {
        const m = String(is_monitored) === 'true'
        items = items.filter(t => (t.is_monitored ?? true) === m)
      }
      const start = (page - 1) * size
      const paged = items.slice(start, start + size)
      return {
        code: 200,
        message: 'success',
        data: {
          items: paged,
          pagination: {
            page,
            size,
            total: items.length,
            pages: Math.max(1, Math.ceil(items.length / size))
          }
        },
        timestamp: new Date().toISOString()
      }
    }
  },
  
  // Flink相关
  flink: {
    getJobs: async (params?: any): Promise<ApiResponse<PaginationResponse<FlinkJob>>> => {
      await delay(200)
      const { page = 1, size = 20, search = '', status, autoRecovery, dateRange } = params || {}
      let items = mockFlinkJobs.slice()
      if (search) {
        const s = String(search).toLowerCase()
        items = items.filter(j => (j.job_name?.toLowerCase().includes(s) || j.job_id?.toLowerCase().includes(s)))
      }
      if (status) {
        items = items.filter(j => j.last_status === status)
      }
      if (autoRecovery !== undefined && autoRecovery !== '') {
        const ar = String(autoRecovery) === 'true'
        items = items.filter(j => j.auto_recovery === ar)
      }
      if (Array.isArray(dateRange) && dateRange.length === 2) {
        const [start, end] = dateRange
        const startMs = new Date(start).getTime()
        const endMs = new Date(end).getTime()
        items = items.filter(j => {
          if (!j.last_check_time) return false
          const t = new Date(j.last_check_time).getTime()
          return t >= startMs && t <= endMs
        })
      }
      const startIdx = (page - 1) * size
      const paged = items.slice(startIdx, startIdx + size)
      return {
        code: 200,
        message: 'success',
        data: {
          items: paged,
          pagination: {
            page,
            size,
            total: items.length,
            pages: Math.max(1, Math.ceil(items.length / size))
          }
        },
        timestamp: new Date().toISOString()
      }
    },

    // 获取作业统计
    getJobStats: async (): Promise<ApiResponse<any>> => {
      await delay(200)
      return {
        code: 200,
        message: 'success',
        data: {
          total_jobs: mockFlinkJobs.length,
          running_jobs: mockFlinkJobs.filter(job => job.last_status === 'RUNNING').length,
          stopped_jobs: mockFlinkJobs.filter(job => job.last_status === 'FINISHED' || job.last_status === 'MANUALLY_STOPPED').length,
          failed_jobs: mockFlinkJobs.filter(job => job.last_status === 'FAILED').length,
          healthy_jobs: mockFlinkJobs.filter(job => job.health_status === 'HEALTHY').length,
          unhealthy_jobs: mockFlinkJobs.filter(job => job.health_status === 'UNHEALTHY').length,
          critical_jobs: mockFlinkJobs.filter(job => job.health_status === 'CRITICAL').length
        },
        timestamp: new Date().toISOString()
      }
    }
  },

  // 告警相关 - 增强版
  alert: {
    getRules: async (params?: any): Promise<ApiResponse<any>> => {
      await delay(200)
      const all = [
        { id: 1, name: '数据量异常告警', description: '表日增量超过阈值', rule_type: 'data_volume', severity: 'HIGH', is_active: true, created_at: '2024-01-10' },
        { id: 2, name: 'Flink作业失败告警', description: 'Flink作业失败触发', rule_type: 'flink_job', severity: 'CRITICAL', is_active: true, created_at: '2024-01-12' },
        { id: 3, name: '数据延迟告警', description: '超过2小时无更新', rule_type: 'data_delay', severity: 'MEDIUM', is_active: false, created_at: '2024-01-13' },
        { id: 4, name: '自定义规则A', description: '自定义SQL检测', rule_type: 'custom', severity: 'LOW', is_active: true, created_at: '2024-01-14' }
      ]
      const { page = 1, size = 20, search = '', severity, status } = params || {}
      let items = all.slice()
      if (search) {
        const s = String(search).toLowerCase()
        items = items.filter(r => r.name.toLowerCase().includes(s) || (r.description?.toLowerCase().includes(s)))
      }
      if (severity) items = items.filter(r => r.severity === severity)
      if (status !== undefined && status !== '') {
        const st = String(status) === 'true'
        items = items.filter(r => r.is_active === st)
      }
      const start = (page - 1) * size
      return {
        code: 200,
        message: 'success',
        data: {
          items: items.slice(start, start + size),
          pagination: { page, size, total: items.length, pages: Math.max(1, Math.ceil(items.length / size)) }
        },
        timestamp: new Date().toISOString()
      }
    },

    getHistory: async (params?: any): Promise<ApiResponse<any>> => {
      await delay(200)
      const all = Array.from({ length: 28 }).map((_, i) => ({
        id: i + 1,
        title: i % 2 === 0 ? '数据量异常告警' : 'Flink作业失败告警',
        layer: i % 3 === 0 ? 'ODS' : i % 3 === 1 ? 'DWD' : 'DWS',
        table_name: i % 2 === 0 ? 'ods_event_log' : 'dwd_order_detail',
        severity: i % 4 === 0 ? 'CRITICAL' : i % 3 === 0 ? 'HIGH' : i % 2 === 0 ? 'MEDIUM' : 'LOW',
        status: i % 3 === 0 ? 'ACTIVE' : i % 3 === 1 ? 'RESOLVED' : 'ACKNOWLEDGED',
        triggered_at: new Date(Date.now() - i * 3600 * 1000).toISOString()
      }))
      const { page = 1, size = 20, severity, status, search = '' } = params || {}
      let items = all
      if (severity) items = items.filter(a => a.severity === severity)
      if (status) items = items.filter(a => a.status === status)
      if (search) {
        const s = String(search).toLowerCase()
        items = items.filter(a => a.title.toLowerCase().includes(s) || a.table_name.toLowerCase().includes(s))
      }
      const start = (page - 1) * size
      return {
        code: 200,
        message: 'success',
        data: {
          items: items.slice(start, start + size),
          pagination: { page, size, total: items.length, pages: Math.max(1, Math.ceil(items.length / size)) }
        },
        timestamp: new Date().toISOString()
      }
    },

    getTemplates: async (params?: any): Promise<ApiResponse<any>> => {
      await delay(200)
      const all = [
        { id: 1, name: '数据异常模板', description: '数据异常告警标准模板', template_type: 'wechat', is_active: true },
        { id: 2, name: '作业失败模板', description: '作业失败告警标准模板', template_type: 'wechat', is_active: true },
        { id: 3, name: '数据延迟模板', description: '数据延迟告警模板', template_type: 'wechat', is_active: false }
      ]
      const { page = 1, size = 20, search = '' } = params || {}
      let items = all
      if (search) {
        const s = String(search).toLowerCase()
        items = items.filter(t => t.name.toLowerCase().includes(s) || (t.description?.toLowerCase().includes(s)))
      }
      const start = (page - 1) * size
      return {
        code: 200,
        message: 'success',
        data: {
          items: items.slice(start, start + size),
          pagination: { page, size, total: items.length, pages: Math.max(1, Math.ceil(items.length / size)) }
        },
        timestamp: new Date().toISOString()
      }
    }
  },

  // 报表相关 - 增强版
  report: {
    getReports: async (params?: any): Promise<ApiResponse<any>> => {
      await delay(200)
      const all = Array.from({ length: 26 }).map((_, i) => ({
        id: i + 1,
        name: i % 2 === 0 ? '数据质量日报' : '系统性能周报',
        description: i % 2 === 0 ? '每日数据质量监控报告' : '每周系统性能分析报告',
        report_type: i % 3 === 0 ? 'data_report' : i % 3 === 1 ? 'chart_report' : 'custom_report',
        is_active: i % 5 !== 0,
        created_at: new Date(Date.now() - i * 86400 * 1000).toISOString()
      }))
      const { page = 1, size = 20, search = '', reportType, status, dateRange } = params || {}
      let items = all
      if (search) {
        const s = String(search).toLowerCase()
        items = items.filter(r => r.name.toLowerCase().includes(s) || (r.description?.toLowerCase().includes(s)))
      }
      if (reportType) items = items.filter(r => r.report_type === reportType)
      if (status !== undefined && status !== '') {
        const st = String(status) === 'true'
        items = items.filter(r => r.is_active === st)
      }
      if (Array.isArray(dateRange) && dateRange.length === 2) {
        const [start, end] = dateRange
        const startMs = new Date(start).getTime()
        const endMs = new Date(end).getTime()
        items = items.filter(r => {
          const t = new Date(r.created_at).getTime()
          return t >= startMs && t <= endMs
        })
      }
      const start = (page - 1) * size
      return {
        code: 200,
        message: 'success',
        data: {
          items: items.slice(start, start + size),
          pagination: { page, size, total: items.length, pages: Math.max(1, Math.ceil(items.length / size)) }
        },
        timestamp: new Date().toISOString()
      }
    },

    getTemplates: async (params?: any): Promise<ApiResponse<any>> => {
      await delay(200)
      const all = [
        { id: 1, name: 'CSV数据报表模板', description: 'CSV格式模板', template_type: 'csv', is_active: true },
        { id: 2, name: 'Excel数据报表模板', description: 'Excel格式模板', template_type: 'excel', is_active: true },
        { id: 3, name: 'HTML数据报表模板', description: 'HTML格式模板', template_type: 'html', is_active: false }
      ]
      const { page = 1, size = 20, search = '' } = params || {}
      let items = all
      if (search) {
        const s = String(search).toLowerCase()
        items = items.filter(t => t.name.toLowerCase().includes(s) || (t.description?.toLowerCase().includes(s)))
      }
      const start = (page - 1) * size
      return {
        code: 200,
        message: 'success',
        data: {
          items: items.slice(start, start + size),
          pagination: { page, size, total: items.length, pages: Math.max(1, Math.ceil(items.length / size)) }
        },
        timestamp: new Date().toISOString()
      }
    }
  },

  // 系统管理相关 - 增强版
  system: {
    getConfigs: async (params?: any): Promise<ApiResponse<any>> => {
      await delay(200)
      const all = [
        { id: 1, config_key: 'system_name', config_value: 'YC数据平台', description: '系统名称', category: 'system' },
        { id: 2, config_key: 'max_connections', config_value: '100', description: '最大数据库连接数', category: 'database' },
        { id: 3, config_key: 'default_monitor_interval', config_value: '300', description: '默认监控间隔', category: 'monitor' }
      ]
      const { page = 1, size = 20, search = '' } = params || {}
      let items = all
      if (search) {
        const s = String(search).toLowerCase()
        items = items.filter(c => c.config_key.toLowerCase().includes(s) || (c.description?.toLowerCase().includes(s)))
      }
      const start = (page - 1) * size
      return {
        code: 200,
        message: 'success',
        data: {
          items: items.slice(start, start + size),
          pagination: { page, size, total: items.length, pages: Math.max(1, Math.ceil(items.length / size)) }
        },
        timestamp: new Date().toISOString()
      }
    },

    getDatabaseConfigs: async (params?: any): Promise<ApiResponse<any>> => {
      await delay(200)
      const all = [
        { id: 1, name: 'StarRocks主库', db_type: 'starrocks', host: '192.168.1.100', port: 9030, is_active: true, is_default: true },
        { id: 2, name: 'MySQL配置库', db_type: 'mysql', host: '192.168.1.101', port: 3306, is_active: true, is_default: false },
        { id: 3, name: 'Redis缓存', db_type: 'redis', host: '192.168.1.102', port: 6379, is_active: false, is_default: false }
      ]
      const { page = 1, size = 20, search = '', dbType, status, isDefault } = params || {}
      let items = all
      if (search) {
        const s = String(search).toLowerCase()
        items = items.filter(d => d.name.toLowerCase().includes(s) || d.host.toLowerCase().includes(s))
      }
      if (dbType) items = items.filter(d => d.db_type === dbType)
      if (status !== undefined && status !== '') {
        const st = String(status) === 'true'
        items = items.filter(d => d.is_active === st)
      }
      if (isDefault !== undefined && isDefault !== '') {
        const def = String(isDefault) === 'true'
        items = items.filter(d => d.is_default === def)
      }
      const start = (page - 1) * size
      return {
        code: 200,
        message: 'success',
        data: {
          items: items.slice(start, start + size),
          pagination: { page, size, total: items.length, pages: Math.max(1, Math.ceil(items.length / size)) }
        },
        timestamp: new Date().toISOString()
      }
    },

    getWechatBots: async (params?: any): Promise<ApiResponse<any>> => {
      await delay(200)
      const all = [
        { id: 1, name: '运维告警机器人', description: '用于发送运维告警通知', is_active: true },
        { id: 2, name: '数据监控机器人', description: '用于发送数据监控通知', is_active: true },
        { id: 3, name: '报表推送机器人', description: '用于发送报表通知', is_active: false }
      ]
      const { page = 1, size = 20, search = '', status } = params || {}
      let items = all
      if (search) {
        const s = String(search).toLowerCase()
        items = items.filter(w => w.name.toLowerCase().includes(s) || (w.description?.toLowerCase().includes(s)))
      }
      if (status !== undefined && status !== '') {
        const st = String(status) === 'true'
        items = items.filter(w => w.is_active === st)
      }
      const start = (page - 1) * size
      return {
        code: 200,
        message: 'success',
        data: {
          items: items.slice(start, start + size),
          pagination: { page, size, total: items.length, pages: Math.max(1, Math.ceil(items.length / size)) }
        },
        timestamp: new Date().toISOString()
      }
    }
  },

  // 任务相关 - 新增 mock
  task: {
    getTasks: async (params?: any): Promise<ApiResponse<PaginationResponse<any>>> => {
      await delay(200)
      const tasks = Array.from({ length: 35 }).map((_, i) => ({
        id: i + 1,
        queryId: `Q${1000 + i}`,
        taskName: i % 3 === 0 ? 'data_sync_task' : i % 3 === 1 ? 'report_gen_task' : 'backup_task',
        createTime: new Date(Date.now() - i * 3600 * 1000).toISOString(),
        finishTime: i % 5 === 0 ? undefined : new Date(Date.now() - (i - 1) * 3500 * 1000).toISOString(),
        state: i % 5 === 0 ? 'FAILED' : i % 4 === 0 ? 'CANCELLED' : i % 3 === 0 ? 'RUNNING' : 'FINISHED',
        catalog: 'default',
        database: i % 2 === 0 ? 'test' : 'prod',
        definition: 'SELECT * FROM table',
        errorMessage: i % 5 === 0 ? 'Network timeout' : undefined
      }))
      const { page = 1, size = 20, search = '' } = params || {}
      let filtered = tasks
      if (search) {
        const s = String(search).toLowerCase()
        filtered = tasks.filter(t => t.taskName.toLowerCase().includes(s) || t.queryId.toLowerCase().includes(s))
      }
      const start = (page - 1) * size
      return {
        code: 200,
        message: 'success',
        data: {
          items: filtered.slice(start, start + size),
          pagination: {
            page,
            size,
            total: filtered.length,
            pages: Math.max(1, Math.ceil(filtered.length / size))
          }
        },
        timestamp: new Date().toISOString()
      }
    }
  },

} 